<template>
  <div class="goodsInfo">
    <a-card title="商品信息" size="small">
      <c-desc :data="descData" :column="2" :columns="productInfo">
        <template v-for="i in productInfoSlots" #[i.prop]>
          <span :key="i.prop">
            <span style="padding-right:6px;" v-if="label(i)"
              >{{ label(i) }}
            </span>
            <span
              class="danger"
              v-if="auditLabel(i) && label(i) !== auditLabel(i)"
              >(修改为{{ auditLabel(i) }})</span
            >
            <span v-if="!label(i) && !auditLabel(i)">--</span>
          </span>
        </template>
        <template #warehouse>
          <span style="padding-right:6px;">
            {{ descData.warehouse && descData.warehouse.shortName }}
          </span>
          <template v-if="isLine()">
            <span
              class="danger"
              v-if="
                auditData.warehouse &&
                  auditData.warehouse.id !==
                    (descData.warehouse && descData.warehouse.id)
              "
            >
              (修改为{{ auditData.warehouse.shortName }})
            </span>
          </template>
          <template v-else>
            <span
              class="danger"
              v-if="
                auditData.warehouseId &&
                  auditData.warehouseId !==
                    (descData.warehouse && descData.warehouse.id)
              "
            >
              (修改为{{ auditData.warehouseShortName }})
            </span>
          </template>
        </template>
      </c-desc>
      <a-space slot="extra">
        <!-- 线路订单 -->
        <template v-if="isLine()">
          <template
            v-if="
              isSeller() &&
                orderDetail.orderStatus ===
                  orderDict.pricingStatus.waitContract.value &&
                !orderDetail.auditLineOrder
            "
          >
            <c-button
              type="primary"
              @click="openUpdatePremium"
              v-if="
                $verifyBtn('sellerPricingModifyPremiumByLine') &&
                  orderDetail.priceType ===
                    quotationDict.priceType.pricing.value
              "
            >
              修改升贴水
            </c-button>
            <c-button
              type="primary"
              @click="openModal"
              v-if="
                $verifyBtn('sellerPricingModifyGoodsByLine') &&
                  relevanceInventoryList.length === 0
              "
              >修改商品</c-button
            >
            <c-button
              type="primary"
              @click="openModifyPrice"
              v-if="
                $verifyBtn('sellerApplyModifyBasePriceByLine') &&
                  isSeller() &&
                  orderDetail.orderStatus ===
                    orderDict.pricingStatus.waitContract.value &&
                  orderDetail.priceType ===
                    quotationDict.priceType.pricing.value
              "
            >
              修改价格
            </c-button>
            <c-button
              type="primary"
              @click="openModifyPrice"
              v-if="
                $verifyBtn('sellerApplyModifyFirmPriceByLine') &&
                  isSeller() &&
                  orderDetail.orderStatus ===
                    orderDict.pricingStatus.waitContract.value &&
                  orderDetail.priceType ===
                    quotationDict.priceType.confirm.value
              "
            >
              修改价格
            </c-button>
          </template>
        </template>
        <!-- 普通订单 -->
        <template v-else>
          <c-button
            type="primary"
            @click="openUpdatePremium"
            v-if="
              $verifyBtn('sellerPricingModifyPremium') &&
                isSeller() &&
                orderDetail.orderStatus ===
                  orderDict.pricingStatus.waitContract.value &&
                orderDetail.priceType === quotationDict.priceType.pricing.value
            "
          >
            修改升贴水
          </c-button>
          <c-button
            type="primary"
            @click="openModal"
            v-if="
              ($verifyBtn('sellerPricingModifyGoods') ||
                $verifyBtn('sellerConfirmModifyGoods')) &&
                isSeller() &&
                orderDetail.orderStatus ===
                  orderDict.pricingStatus.waitContract.value &&
                relevanceInventoryList.length === 0
            "
            >修改商品</c-button
          >
          <c-button
            type="primary"
            @click="openModifyPrice"
            v-if="
              $verifyBtn('sellerApplyModifyBasePrice') &&
                isSeller() &&
                orderDetail.orderStatus ===
                  orderDict.pricingStatus.waitContract.value &&
                orderDetail.priceType === quotationDict.priceType.pricing.value
            "
          >
            修改价格
          </c-button>
          <c-button
            type="primary"
            @click="openModifyPrice"
            v-if="
              $verifyBtn('sellerApplyModifyFirmPrice') &&
                isSeller() &&
                orderDetail.orderStatus ===
                  orderDict.pricingStatus.waitContract.value &&
                orderDetail.priceType === quotationDict.priceType.confirm.value
            "
          >
            修改价格
          </c-button>
        </template>
      </a-space>
    </a-card>
    <c-modal
      v-model="visible"
      title="修改订单商品"
      @ok="updateGoods"
      :okLoading="updateGoodsLoading"
    >
      <c-form v-model="form" :data="formData">
        <template v-for="(val, key) in selectList" v-slot:[key]>
          <cSelectCreate
            v-model="form[key]"
            :data="selectList[key]"
            :placeholder="
              '请输入' +
                (key === 'brand'
                  ? '品牌'
                  : key === 'spec'
                  ? '规格'
                  : key === 'material'
                  ? '材质'
                  : '其他')
            "
            :key="key"
          />
        </template>
        <template v-slot:warehouse>
          <a-select
            v-model="form.warehouseId"
            showSearch
            optionFilterProp="children"
          >
            <a-select-option
              v-for="item in warehouseList"
              :value="item.id"
              :key="item.id"
            >
              {{ item.shortName }}
            </a-select-option>
          </a-select>
        </template>
      </c-form>
    </c-modal>
    <c-modal
      v-model="premiumVisible"
      title="修改升贴水"
      @ok="updatePremium"
      :okLoading="updatePremiumLoading"
      :width="300"
    >
      <c-desc :data="orderDetail" :column="1" :columns="updatePremiumDesc">
        <template v-slot:updatePremiumAmount>
          <a-input
            v-model="updatePremiumAmount"
            type="number"
            placeholder="请输入升贴水"
            style="width: 130px;"
          >
          </a-input>
        </template>
      </c-desc>
    </c-modal>
  </div>
</template>

<script>
import cSelectCreate from "@/components/select-create";
import quotationDict from "@/dict/quotation";
import orderDict from "@/dict/order";
import {
  providerapplyalterslideorder,
  providerapplyalterconfirmorder,
  providerqueryorderauditdata,
  customerqueryorderauditdata,
  providerapplyalterpremium
} from "@/api/order/modifyGoods";
import {
  providerapplyalterlineorderpremium,
  providerapplyalterlineorder,
  providerapplyalterlineorderbaseprice,
  providerapplyalterlineorderfirmprice
} from "@/api/order-line";
import {
  providerapplyalterconfirmfirmprice,
  providerapplyalterslidebaseprice
} from "@/api/order/modifyPrice";
import { isSeller, isLine } from "@/util/common";
import { getcategoryattr } from "@/api/quotation";
import { getcompanywarehouses } from "@/api/warehouse";
import { modifyPrice } from "./mixin/modifyPrice.js";

export default {
  components: {
    cSelectCreate
  },
  props: {
    // 订单信息
    orderDetail: {
      type: Object
    },
    // 已关联的实物库存
    relevanceInventoryList: {
      type: Array,
      default: () => {
        return [];
      }
    }
  },
  mixins: [modifyPrice],
  data() {
    return {
      orderDict,
      quotationDict,
      visible: false, // 修改商品弹窗
      updateGoodsLoading: false,
      premiumVisible: false, // 修改升贴水弹窗
      updatePremiumLoading: false,
      updatePremiumAmount: undefined, // 修改的升贴水
      auditData: {}, // 待审核订单信息
      form: {
        brand: undefined,
        spec: undefined,
        material: undefined,
        other: undefined,
        warehouseId: undefined,
        // premium: undefined,
        deliveryType: undefined,
        invoiceType: undefined,
        settlementType: undefined,
        quotationRemark: undefined
      },
      formData: [
        {
          label: "品牌",
          prop: "brand",
          slot: "brand"
        },
        {
          label: "规格",
          prop: "spec",
          slot: "spec"
        },
        {
          label: "材质",
          prop: "material",
          slot: "material"
        },
        {
          label: "其他",
          prop: "other",
          slot: "other"
        },
        {
          label: "仓库简称",
          prop: "warehouse",
          slot: "warehouse"
        },
        // {
        //   label: "升贴水",
        //   prop: "premium"
        // },
        {
          label: "交货方式",
          prop: "deliveryType",
          slot: "deliveryType"
        },
        {
          label: "开票日期",
          prop: "invoiceType",
          slot: "invoiceType"
        },
        {
          label: "结算方式",
          prop: "settlementType",
          slot: "settlementType"
        }
      ],
      selectList: {
        brand: [],
        spec: [],
        material: [],
        other: [],
        deliveryType: [
          {
            title: "卖家送货",
            value: "卖家送货"
          },
          {
            title: "买家自提",
            value: "买家自提"
          },
          {
            title: "转货权",
            value: "转货权"
          }
        ],
        settlementType: [
          {
            title: "电汇",
            value: "电汇"
          },
          {
            title: "转账",
            value: "转账"
          },
          {
            title: "承兑",
            value: "承兑"
          }
        ],
        invoiceType: [
          {
            title: "下月开票",
            value: "下月开票"
          },
          {
            title: "本月开票",
            value: "本月开票"
          }
        ]
      },
      warehouseList: [],
      updatePremiumDesc: [
        {
          label: "原订单升贴水",
          prop: "premium"
        },
        {
          label: "修改订单升贴水",
          slot: "updatePremiumAmount"
        }
      ]
    };
  },
  computed: {
    descData() {
      let res;
      // 是否有待审核商品信息
      // if (this.isAudit) {
      //   let original = Object.assign({}, this.orderDetail);
      //   res = Object.assign(original, this.auditData);
      // } else {
      res = this.orderDetail;
      // }
      return res;
    },
    productInfo() {
      let res = [
        {
          label: "商品",
          prop: "categoryName"
        },
        {
          label: "品牌",
          prop: "brand",
          slot: "brand"
        },
        {
          label: "规格",
          prop: "spec",
          slot: "spec"
        },
        {
          label: "材质",
          prop: "material",
          slot: "material"
        },
        {
          label: "其他",
          prop: "other",
          slot: "other"
        },
        {
          label: "仓库",
          prop: "warehouse",
          slot: "warehouse"
        },
        {
          label: "升贴水",
          prop: "premium",
          hidden:
            this.orderDetail.priceType !==
            quotationDict.priceType.pricing.value,
          slot: "premium"
        },
        {
          label: "备注",
          prop: "quotationRemark",
          slot: "quotationRemark"
        },
        {
          label: "交货方式",
          prop: "deliveryType",
          slot: "deliveryType"
        },
        {
          label: "结算方式",
          prop: "settlementType",
          slot: "settlementType"
        },
        {
          label: "开票日期",
          prop: "invoiceType",
          slot: "invoiceType"
        },
        {
          label: "订单备注",
          prop: isSeller() ? "providerRemark" : "customerRemark"
        }
      ];
      return res;
    },
    // 是否有待审核商品信息
    isAudit() {
      return (
        this.orderDetail.orderStatus ===
          orderDict.pricingStatus.modifyGoods.value ||
        this.orderDetail.orderStatus ===
          orderDict.pricingStatus.modifyPremium.value
      );
    },
    productInfoSlots() {
      let res = this.productInfo.filter(i => i.prop !== "warehouse");
      return res;
    },
    label() {
      return val => {
        let res = this.orderDetail[val.prop];
        return res;
      };
    },
    auditLabel() {
      return val => {
        let res = this.auditData[val.prop];
        return res;
      };
    }
  },
  methods: {
    isLine,
    isSeller,
    // 修改价格
    openModifyPrice() {
      let type = this.orderDetail.priceType;
      let request =
        this.orderDetail.priceType ===
        this.quotationDict.priceType.pricing.value
          ? this.isLine()
            ? providerapplyalterlineorderbaseprice
            : providerapplyalterslidebaseprice
          : this.isLine()
          ? providerapplyalterlineorderfirmprice
          : providerapplyalterconfirmfirmprice;
      this.modifyPriceHandle(type, request, this.isLine());
    },
    // 打开修改升贴水弹窗
    openUpdatePremium() {
      this.premiumVisible = true;
    },
    // 提交修改升贴水
    updatePremium() {
      this.updatePremiumLoading = true;
      let request = this.isLine()
        ? providerapplyalterlineorderpremium
        : providerapplyalterpremium;
      request({
        orderId: this.isLine() ? undefined : this.orderDetail.id,
        id: this.isLine() ? this.orderDetail.id : undefined,
        version: this.orderDetail.version,
        premium: this.updatePremiumAmount
      })
        .then(res => {
          this.$message.success("操作成功");
          this.premiumVisible = false;
          this.$emit("handleSuccess", {
            data: res,
            type: this.isLine() ? "updateLineOrderPremium" : "updatePremium"
          });
        })
        .finally(() => {
          this.updatePremiumLoading = false;
        });
    },
    //   提交修改商品
    updateGoods() {
      let request = this.isLine()
        ? providerapplyalterlineorder
        : this.orderDetail.priceType === quotationDict.priceType.pricing.value
        ? providerapplyalterslideorder
        : providerapplyalterconfirmorder;
      this.updateGoodsLoading = true;
      let params;
      if (this.isLine()) {
        params = {
          id: this.orderDetail.id,
          version: this.orderDetail.version,
          ...this.form
        };
      } else {
        params = {
          orderId: this.orderDetail.id,
          version: this.orderDetail.version,
          alterOrder: this.form
        };
      }
      request(params)
        .then(res => {
          this.$message.success("操作成功");
          this.visible = false;
          this.$emit("handleSuccess", {
            data: res,
            type: this.isLine() ? "updateLineOrderGoods" : "updateGoods"
          });
        })
        .finally(() => {
          this.updateGoodsLoading = false;
        });
    },
    // 获取仓库下拉框选项
    getAllWarehouse() {
      getcompanywarehouses().then(res => {
        this.warehouseList = res;
      });
    },
    getAttrs() {
      // 设置各属性的下拉框选项
      getcategoryattr({
        categoryId: this.orderDetail.categoryId
      }).then(res => {
        let format = function(type) {
          let data = res
            .filter(i => i.categoryAttrType === type)
            .map(i => i.attrValue);
          let arr = [];
          data.forEach(i => {
            arr.push({
              title: i,
              value: i
            });
          });
          return arr;
        };
        this.selectList.brand = format(1);
      });
    },
    openModal() {
      this.visible = true;
      //   回写商品信息
      for (const key in this.form) {
        if (key === "warehouseId") {
          this.form[key] = this.orderDetail.warehouse.id;
        } else {
          this.form[key] = this.orderDetail[key];
        }
      }
    },
    // 查询订单审核修改信息
    queryOrderAuditData() {
      let request = this.isSeller()
        ? providerqueryorderauditdata
        : customerqueryorderauditdata;
      request({
        orderId: this.orderDetail.id,
        version: this.orderDetail.version
      }).then(res => {
        this.auditData = res;
      });
    },
    init() {
      if (
        (this.$verifyBtn("sellerPricingModifyGoods") ||
          this.$verifyBtn("sellerConfirmModifyGoods")) &&
        this.isSeller() &&
        this.orderDetail.orderStatus ===
          this.orderDict.pricingStatus.waitContract.value
      ) {
        this.getAllWarehouse();
        this.getAttrs();
      }
    }
  },
  created() {
    if (isLine()) {
      // 存在auditLineOrder说明当前订单处于待审核状态
      if (this.orderDetail.auditLineOrder)
        this.auditData = this.orderDetail.auditLineOrder;
    } else {
      // 处于待生成合同-修改商品中时才查询
      if (this.isAudit) {
        this.queryOrderAuditData();
      }
    }
    this.init();
  }
};
</script>
